<?php

class Config implements ArrayAccess
{

  protected $data = array();

  public function copyAll($data)
  {
    foreach ($data as $name => &$value) {
      $this->set($name, $value);
    }
  }

  public function del($name)
  {
    unset($this->data[$name]);
  }

  public function & get($name, $default = null)
  {
    $value =& $this->data[$name];

    if (is_string($value)) {
      $value = $this->resolveReferences($value);
    }

    return $value;
  }

  public function & getData()
  {
    return $this->data;
  }

  public function has($name)
  {
    return isset($this->data[$name]);
  }

  public function offsetExists($offset)
  {
    return $this->has($offset);
  }

  public function & offsetGet($offset)
  {
    return $this->get($offset);
  }

  public function offsetSet($offset, $value)
  {
    $this->set($offset, $value);
  }

  public function offsetUnset($offset)
  {
    $this->del($offset);
  }

  protected function resolveReferences($value)
  {
    while (($s = strpos($value, '{')) !== false) {
      if (($f = strpos($value, '}', $s)) !== false) {
        $name = substr($value, $s + 1, $f - $s - 1);
        $value = str_replace('{' . $name . '}', $this->get($name), $value);
      }
    }

    return $value;
  }

  public function set($name, $value = null)
  {
    $this->data[$name] = & $value;
  }

  public function setData(&$data)
  {
    $this->data =& $data;
  }

}
